<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleConfirm"
    width="60%"
  >
    <template #title>
      <div>
        <div style="margin-bottom: 8px">
          <Icon :icon="getTitle.icon" class="pr-1 m-1" />
          <span> {{ getTitle.value }} </span>
        </div>
        <div
          v-if="record.exceptionRemarks"
          style="
            background: #fff7e6;
            border: 1px solid #ffd591;
            border-radius: 4px;
            padding: 8px 12px;
            color: #d46b08;
            font-size: 13px;
            font-weight: 500;
            margin-top: 8px;
          "
        >
          <Icon
            icon="ant-design:exclamation-circle-outlined"
            style="margin-right: 6px; color: #fa8c16"
          />
          上报原因：{{ record.exceptionRemarks }}
        </div>
      </div>
    </template>
    <BasicForm @register="registerForm">
      <template #userRoleString>
        <BasicTable @register="registerUserRoleTable" />
      </template>
    </BasicForm>

    <!-- 自定义底部按钮 -->
    <template #insertFooter>
      <a-button
        type="default"
        danger
        style="margin-right: 8px; border-color: #ff7875; color: #ff7875; font-weight: 500"
        @click="handleIgnoreClick"
      >
        {{ t('忽略') }}
      </a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsVkeExceptionInfoForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, useTable } from '/@/components/Table';
  import { studentUserSave, studentUserForm } from '/@/api/vke/studentUser';
  import { checkLoginCode } from '/@/api/sys/user';

  const emit = defineEmits(['success', 'register', 'ignore', 'process']);

  const { t } = useI18n('vke.exceptionInfo');
  const { showMessage } = useMessage();
  const record = ref<any>({});
  const op = ref('edit');

  const avatar = ref<any>({});

  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('编辑学生'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('登录账号'),
      field: 'loginCode',
      component: 'Input',
      componentProps: {
        maxlength: 20,
      },
      rules: [
        { required: true },
        { min: 4, max: 20, message: t('请输入长度在 4 到 20 个字符之间') },
        { pattern: /^[\u0391-\uFFE5\w]+$/, message: t('不能输入特殊字符') },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              if (!value || value === '') return resolve();
              checkLoginCode(record.value.loginCode || '', value)
                .then((res) => (res ? resolve() : reject(t('登录账号已存在'))))
                .catch((err) => reject(err.message || t('验证失败')));
            });
          },
        },
      ],
    },
    {
      label: t('用户昵称'),
      field: 'userName',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      required: true,
    },
    {
      label: t('学号'),
      field: 'vstudent.studentNumber',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      required: true,
    },
    {
      label: t('姓名'),
      field: 'vstudent.studentName',
      component: 'Input',
      componentProps: {
        maxlength: 300,
      },
      required: true,
    },
    {
      label: t('学籍状态'),
      field: 'vstudent.studentStatus',
      component: 'Select',
      componentProps: {
        dictType: 'vke_student_status',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('详细信息'),
      field: 'employeeInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('出生年月'),
      field: 'vstudent.dateBirth',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('性别'),
      field: 'vstudent.sex',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'sys_user_sex',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('年级'),
      field: 'vstudent.grade',
      component: 'Select',
      componentProps: {
        dictType: 'vke_grade',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('班级'),
      field: 'vstudent.classCode',
      component: 'Select',
      componentProps: {
        dictType: 'vke_class',
        allowClear: true,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('身份证号'),
      field: 'vstudent.identityCard',
      component: 'Input',
      componentProps: {
        maxlength: 32,
      },
      ifShow: () => op.value === 'add' || op.value === 'edit',
    },
    {
      label: t('角色信息'),
      field: 'roleInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => op.value === 'add' || op.value === 'auth',
    },
    {
      label: t('分配角色'),
      field: 'userRoleString',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'userRoleString',
      show: () => op.value === 'add' || op.value === 'auth',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
    labelWidth: 120,
  });

  const [registerUserRoleTable, userRoleTable] = useTable({
    columns: [
      {
        title: t('角色名称'),
        dataIndex: 'name',
        width: 260,
        align: 'center',
      },
      {
        title: t('角色编码'),
        dataIndex: 'id',
        width: 260,
        align: 'center',
      },
    ],
    rowSelection: { type: 'checkbox' },
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    userRoleTable.setTableData([]);
    userRoleTable.setSelectedRowKeys([]);
    setDrawerProps({ loading: true });
    op.value = data.op || 'edit';

    console.log('表单接收到的数据:', data);

    try {
      // 只传递API需要的基本参数
      const apiParams = {
        userCode: data.userCode,
        op: data.op,
      };

      // 调用API获取完整的学生用户数据（与studentUser保持一致）
      const res = await studentUserForm(apiParams);
      console.log('API返回的数据:', res);

      // 从API返回结果中提取 studentUser 对象（与studentUser保持一致）
      record.value = ((res as any).studentUser || res) as any;

      // 如果有异常记录，将异常记录的ID和上报原因保存到record中
      if (data.exceptionRecord) {
        record.value.exceptionId = data.exceptionRecord.id;
        record.value.exceptionRemarks = data.exceptionRecord.remarks;
        console.log('设置异常记录信息:', {
          exceptionId: record.value.exceptionId,
          exceptionRemarks: record.value.exceptionRemarks,
        });
      }

      setFieldsValue(record.value);
    } catch (error) {
      console.error('获取表单数据失败:', error);
      showMessage('获取表单数据失败');
    }

    updateSchema([
      {
        field: 'loginCode',
        componentProps: {
          disabled: op.value === 'auth',
        },
      },
      {
        field: 'userName',
        componentProps: {
          disabled: op.value === 'auth',
        },
      },
    ]);

    setDrawerProps({ loading: false });
  });

  // 忽略按钮点击处理
  function handleIgnoreClick() {
    console.log('忽略按钮被点击');
    console.log('忽略操作 - record.value:', record.value);
    console.log('忽略操作 - exceptionId:', record.value.exceptionId);

    // 使用 Modal 确认对话框
    Modal.confirm({
      title: '确认忽略',
      content: '确认要忽略此异常信息吗？此操作不可撤销',
      okText: '确认忽略',
      cancelText: '取消',
      onOk: () => {
        const idToIgnore = record.value.exceptionId || record.value.id;
        console.log('忽略操作 - 使用的ID:', idToIgnore);

        if (!idToIgnore) {
          showMessage('无法获取异常记录ID，忽略操作失败');
          return;
        }

        emit('ignore', idToIgnore);
        closeDrawer();
      },
    });
  }

  // 确认按钮（与studentUser保持完全一致）
  async function handleConfirm() {
    try {
      const data = await validate();
      console.log(data);
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        userCode: record.value.userCode,
        op: op.value,
      };

      data.userType = 'student';
      if (op.value === 'add' || op.value === 'auth') {
        data.userRoleString = userRoleTable.getSelectRowKeys().join(',');
      }
      if (op.value === 'add' || op.value == 'edit') {
        data.studentUser_avatar = avatar.value.id;
        data.vstudent.headPortrait = avatar.value.fileUrl;
        data.user = record.value.userCode;
        data.vstudent.studentId = record.value.vstudent.studentId;

        // 简化的家长信息处理（异常信息表单可能不需要复杂的家长逻辑）
        data.vstudent.parentInfo = '';
        if (data.vstudent.parentList) {
          delete data.vstudent.parentList;
        }
      }
      console.log(data);
      const res = await studentUserSave(params, data);
      showMessage((res as any).message);
      setTimeout(closeDrawer);

      // 保存成功后调用已处理方法
      emit('process', record.value.exceptionId || record.value.id);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
